<?php

namespace App\Http\Controllers\Admin;

use App\CodeResponse;
use App\Http\Controllers\Controller;
use App\Models\PracticalTrainingEvaluation;
use App\Models\PracticalTrainingUser;
use App\Services\PracticalTrainingUserService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PracticalTrainingEvaluationController extends AdminController
{
    //保存
    public function  save(Request $request){
        $validator = Validator::make($request->all(), [
            'practical_training_user_id' => 'required|integer|digits_between:1,20|min:1',
            'users_id' => 'required|integer|digits_between:1,20|min:1',
            // 'score' => 'integer',
            'content' => 'string',
            'audit' => 'required|integer',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $putData = $request->except(['_method','_token','course_name']);
        $putData['audit_time'] = Carbon::now()->toDateTimeString();
        $putData['is_finally'] = 1; // 是否是最后一条数据，0 不是 1是
        $id = $request->input('id');
        //添加的时候将原来最后一条标记更新
        if(!isset($id)){
            PracticalTrainingEvaluation::query()
                ->where('is_finally', 1)
                ->update([
                    'is_finally' => 0,
                ]);
        }
     
        $flight = PracticalTrainingEvaluation::updateOrCreate(
            ['id' => $id],
            $putData
        );
        return $this->success($flight->id);
    }

    //删除
    public function  delete(Request $request){
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $practicalTrainingEvaluation = PracticalTrainingEvaluation::find($request->id);
        $practicalTrainingEvaluation->delete();
        return $this->success();
    }
    //列表
    public function  list(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'practical_training_user_id' => 'integer|digits_between:1,20|min:1',
            'page' => 'integer',
            'limit' => 'integer',
            'sort' => 'string',
            'order' => 'string',

        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $name = $request->input('name');
        $practical_training_user_id = $request->input('practical_training_user_id');
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 10);
        $sort = $request->input('sort', 'created_at');
        $order = $request->input('order', 'asc');
        $list = PracticalTrainingUserService::getInstance()->userPracticalEvaluationsList($page, $limit, $sort, $order, $practical_training_user_id);
        return $this->success($list);
    }

}
